import './main.scss'

import {
  ref,
  reactive,
  nextTick,
  watch,
  defineComponent
} from 'vue'

import {
  ElInput,
  ElForm,
  ElCheckboxGroup,
  ElCheckbox,
  ElRadioGroup,
  ElRadio,
  ElMessage,
  ElScrollbar,
  ElTooltip,
  ElSwitch,
  ElTag,
  ElFormItem,
  ElButton
} from 'element-plus'
import {
  createComponentName,
  useExpose
} from '../utils'
import Dialog from '../dialog/Dialog'
import {
  addTags,
  getTagsList
} from '@/api/common'

const [name, bem] = createComponentName('select-tag')

export default defineComponent({
  name,

  props: {
    show: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: true
    },
    showCreatTag: {
      type: Boolean,
      default: false
    },
    selectTags: {
      type: Array,
      default: () => ([])
    }
  },

  emit: [
    'update:show',
    'update:showCreatTag',
    'submit'
  ],

  setup(props, { emit, slots }) {
    const InputRef = ref<InstanceType<typeof ElInput>>()
    const formRef = ref<InstanceType<typeof ElForm>>()
    const inputValue = ref('')
    const inputVisible = ref(false)

    const state = reactive({
      title: '选择标签',
      width: '700px',
      cancelText: '取消',
      submitText: '保存',
      textEdit: false,
      tagsVis: false,
      tagsTitle: '选择标签',
      labelList: [],
      radioTags: {
        defaultVal: 0,
        seleTagOp: [
          {
            name: '批量打标签',
            value: 0,
            text: '若内容本身已有所选标签，则不针对此内容重复打标签'
          },
          {
            name: '批量移除标签',
            value: 1,
            text: '若内容本身没有所选标签，则不针对此内容重复移除标签'
          }
        ]
      },
      isGroup: false,
      groupData: { // 新建分组
        name: '',
        tags: []
      },
      selectTags: []  // 选中标签
    })

    watch(
      () => props.show,
      val => { if(val) tagsList(props.selectTags) }
    )

    watch(
      () => state.labelList,
      val => {
        let res:any = []

        val.forEach((item: any) => {
          if (item.tags && item.tags.length > 0) {
            item.tags.forEach((tag: any) => {
              tag.selected && res.push(tag)
            })
          }
        })

        state.selectTags = res
      },
      { deep: true }
    )

    // 获取标签列表
    const tagsList = async (tags?: any[]) => {
      if (state.labelList.length) return

      const arr: any[] = []

      if (tags && tags.length > 0) {
        tags.forEach((item: any) => {
          arr.push(item.id || item.tag_id)
        })
      }
      let res = await getTagsList({
        page: 1,
        page_size: 100
      })
      state.labelList = res.data
      state.labelList.forEach((item: any) => item.tags.forEach((k: any) => k.selected = arr.includes(k.id)))
    }

    const removeItem = (data: any) => {
      let arr: any[] = []

      state.labelList.forEach((label: any) => {
        if (label.tags?.length) {
          label.tags.forEach((tag: any) => {
            if (tag.id === data.id) {
              tag.selected = false
            }
          })
        }
      })
    }

    const removeAll = () => {
      state.labelList.forEach((label: any) => {
        label.tags?.length && label.tags.forEach((tag: any) => tag.selected = false)
      })
    }

    // 确认
    const onSubmit = async () => {
      // 新增标签
      if (state.isGroup) {
        formRef.value?.validate((valid: any) => {
          if (!valid) return
        })
      }
      // 批量标签
      if (props.multiple) {
        emit('submit', state.selectTags)
      } else {
        emit('submit', {
          tag_ids: state.selectTags,
          defaultVal: state.radioTags.defaultVal,
        })
      }
      state.title = '新建标签'
      state.radioTags.defaultVal = 0
      onCancel()
    }

    // 取消
    const onCancel = () => {
      emit('update:showCreatTag', false)
      formRef.value?.resetFields()
      onClose()
    }

    // 关闭
    const onClose = () => {
      emit('update:show', false)
      emit('close', false)
    }

    // 选择标签
    const onChangeTag = (tags: any) => {
      if (props.multiple) {
        state.selectTags = tags
      } else {
        state.selectTags = tags
        state.radioTags.defaultVal = tags.value
      }
    }

    const handleClose = (tag: string) => {
      const data = state.groupData.tags.filter((item: string) => item !== tag)
      state.groupData.tags = data
    }

    const createLabel = () => {
      inputVisible.value = true
      nextTick(() => {
        InputRef.value!.input!.focus()
      })
    }

    const handleInputConfirm = () => {
      if (inputValue.value) {
        if (state.groupData.tags.includes(inputValue.value)) {
          ElMessage.warning('新建标签名不能重复')
          return
        }
        state.groupData.tags.push(inputValue.value)
      }
      inputVisible.value = false
      inputValue.value = ''
    }

    // 保存新建
    const saveLabel = () => {
      formRef.value?.validate(async (valid: any) => {
        if (valid) {
          try {
            const res = await addTags(state.groupData)
            ElMessage.success('创建标签成功')
            tagsList()
            formRef.value?.resetFields()
          } catch (e) {}
        }
      })
    }

    useExpose({
      removeItem,
      removeAll
    })

    return () => {
      return (
        <Dialog
          vModel:show={ props.show }
          class={ bem() }
          title={ state.title }
          width="700px"
          onConfirm={ onSubmit }
          onCancel={ onCancel }
          onClose={ onClose }
        >
          <div class={ bem('content') }>
            <ElScrollbar maxHeight="400px">
              {
                state.labelList.length || state.radioTags.seleTagOp.length
                  ? props.multiple
                    ? <ElCheckboxGroup
                      vModel={ state.selectTags }
                      class={ bem('tag-list') }
                      onChange={ v => onChangeTag(v) }
                    >
                      {
                        state.labelList.map((item: any) => (
                          item.tags && item.tags.length > 0 && <section
                            class={ bem('tag-item') }
                            key={ item.id }
                          >
                            <div class={ bem('tag-item-title') }>{ item.name }：</div>
                            <ElScrollbar
                              class={ bem('tag-box') }
                              maxHeight="80px"
                            >
                              {
                                item.tags.map((k: any) => (
                                  <ElCheckbox
                                    class={ [bem('tag-item-tag'), k.selected ? bem('tag-item-tag-cur') : ''] }
                                    label={ k }
                                    key={ k.id }
                                    onChange={ () => k.selected = !k.selected }
                                  >
                                    <span class={ bem('tag-text') }>{ k.name }</span>
                                  </ElCheckbox>
                                ))
                              }
                            </ElScrollbar>
                          </section>
                        ))
                      }
                    </ElCheckboxGroup>
                    : <ElRadioGroup
                      vModel={ state.radioTags.defaultVal }
                      class={ bem('tag-list') }
                      onChange={ v => onChangeTag(v) }
                    >
                      {
                        state.radioTags.seleTagOp.map((item: any) => (
                          <ElRadio
                            class={ [bem('tag-item-tag'), item.selected ? bem('tag-item-tag-cur') : ''] }
                            label={ item }
                            key={ item }
                          >
                            <span class={ bem('tag-text') }>{ item.name }</span>
                            <ElTooltip
                              content={ item.text }
                              placement="bottom"
                              effect="light"
                            >
                              <div class={ bem('radio-list-item-icon') }>
                                <img
                                  src="~/assets/image/material/question.png"
                                  alt=""
                                />
                              </div>
                            </ElTooltip>
                          </ElRadio>
                        ))
                      }
                    </ElRadioGroup>
                  : <div class={ bem('empty') }>
                    <img
                      class={ bem('empty-img') }
                      src="~/assets/noData.png"
                      alt=""
                    />
                    <div class={ bem('empty-txt') }>暂无数据</div>
                  </div>
              }
            </ElScrollbar>
            {
              props.showCreatTag && <div class={ bem('new-group') }>
                <div class={ bem('label-title') }>
                  新建分组：
                  <ElSwitch vModel={ state.isGroup } />
                </div>
                {
                  state.isGroup && <ElForm
                    class={ bem('demo-dynamic') }
                    ref={ formRef }
                    model={ state.groupData }
                    labelWidth="100px"
                  >
                    <ElFormItem
                      prop="name"
                      label="分组名称："
                      rules={ [
                        {
                          required: true,
                          message: '分组名称不能为空',
                          trigger: 'blur',
                        }
                      ] }
                      inlineMessage
                      size="small"
                    >
                      <ElInput
                        vModel={ state.groupData.name }
                        class={ bem('group-data-name') }
                        maxlength="15"
                      ></ElInput>
                    </ElFormItem>
                    <ElFormItem
                      prop="tags"
                      label="标签："
                      rules={ [
                        {
                          required: true,
                          message: '标签不能为空',
                          trigger: 'blur'
                        }
                      ] }
                    >
                      {
                        state.groupData.tags.map(tag => (
                          <ElTag
                            closable
                            onClose={ () => handleClose(tag) }
                            key={ tag }
                          >
                            { tag }
                          </ElTag>
                        ))
                      }
                      {
                        inputVisible.value
                          ? <ElInput
                            ref={ InputRef }
                            class={ bem('create-label-input') }
                            vModel={ inputValue.value }
                            size="small"
                            maxlength="15"
                            onKeyup_enter={ handleInputConfirm }
                            onBlur={ handleInputConfirm }
                          />
                          : <ElButton
                            class={ [bem('button-new-tag'), bem('button-new-tag-ml-1')] }
                            size="small"
                            plan
                            onClick={ createLabel }
                          >新建标签</ElButton>
                      }
                    </ElFormItem>
                    <ElFormItem
                      size="small"
                    >
                      <ElButton
                        type="primary"
                        plain
                        onClick={ saveLabel }
                      >保存新建标签</ElButton>
                    </ElFormItem>
                  </ElForm>
                }
              </div>
            }
          </div>
        </Dialog>
      )
    }
  }
})
